/**
 * TODO
 * @Project: topcrazy
 * @Title: SystemLoginController.java
 * @Package net.topcrazy.blog.controller.sys
 * @author notepad
 * @Date Sep 23, 2012 5:43:42 PM
 * @Copyright: 2012 www.topcrazy.net
 * @Version v1.0.0
 */
package net.topcrazy.blog.controller.sys;

import javax.servlet.http.HttpServletRequest;

import net.topcrazy.base.common.BaseController;
import net.topcrazy.base.common.LoginResult;
import net.topcrazy.base.common.SessionGlobal;
import net.topcrazy.blog.service.TsysAccountService;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

/**
 * TODO
 * 
 * @ClassName: SystemLoginController
 * @author notepad
 */
@Controller
@RequestMapping("/sys")
public class SystemLoginController
{

	protected final Logger log = Logger.getLogger(SystemLoginController.class);
	/**
	 * isValidateCode : 是否启用验证码
	 */
	private final boolean isValidateCode = false;
	@Autowired
	private TsysAccountService tsysAccountService;

	/**
	 * 后台系统登录
	 * 
	 * @Title: login
	 * @param request
	 * @param userName
	 *            用户帐号
	 * @param password
	 *            密码
	 * @param validateCode
	 *            验证码
	 * @return {state:true/false,msg:'message'}
	 */
	@RequestMapping(value = "/login")
	@ResponseBody
	public LoginResult login(HttpServletRequest request, String userName, String password, String validateCode)
	{
		LoginResult result = new LoginResult();
		result.setState(false);
		try
		{
			userName = StringUtils.trimToEmpty(userName);
			password = StringUtils.trimToEmpty(password);
			if (StringUtils.isEmpty(userName))
			{
				result.setMsg("帐号未输入");
				return result;
			}
			if (StringUtils.isEmpty(password))
			{
				result.setMsg("密码未输入");
				return result;

			}

			if (isValidateCode)
			{
				validateCode = StringUtils.trimToEmpty(validateCode);
				if (StringUtils.isEmpty(validateCode))
				{
					result.setMsg("验证码未输入");
					return result;
				}
				Object obj = request.getSession().getAttribute("validateCode");
				if (obj != null)
				{
					if (!validateCode.equalsIgnoreCase(obj.toString()))
					{
						result.setMsg("验证码错误");
						return result;
					}
				}
			}
			SessionGlobal xx = new SessionGlobal();
			// request.getSession().setAttribute("sessionGlobal", xx);
			WebUtils.setSessionAttribute(request, "sessionGlobal", xx);
			// 用户验证
			result = tsysAccountService.login(userName, password, xx);
		} catch (Exception e)
		{
			log.error("登录错误", e);
		}
		return result;
	}
}
